#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int Judge(int num)
{
    int count = 1;
    while (num /= 10)
    {
        count++;
    }
    return count;
}
int main() 
{
    int row = 0;
    scanf("%d", &row);
    int arr[1000] = { 0 };
    int i = 0;
    int radix = 0;
    int num = 0;
    char num16[100] = { 0 };
    for (i = 0; i < row; i++)
    {
        scanf("%d", &radix);
        if(radix<=10)
        {
            scanf("%d", &num);
            int count = Judge(num);
            for (int j = 0; j < count; j++)
            {
                arr[i] += (num % 10) * pow(radix, j);
                num /= 10;
            }
        }
        else
        {
            scanf("%s", num16);
            int flag = 0;
            while (num16[flag] != '\0')
            {
                flag++;
            }
            int numflag = flag;
            //printf("%d\n", flag);
            for (int j = 0; j < numflag ; j++,flag--)
            {
                if (num16[flag - 1] >= 'A' && num16[flag - 1]<='Z')
                {
                    num16[flag - 1] -= 55;
                }
                else if (num16[flag - 1] >= '0' && num16[flag - 1]<='9')
                {
                    num16[flag - 1] -= 48;
                }
                else    //if num16[flag - 1] >= 97 && num16[flag - 1] <= 122)
                {
                    num16[flag - 1] = num16[flag - 1] -87;
                }
                arr[i] += num16[flag - 1] * pow(radix, j);
                
            }
        }
    }
    for (i = 0; i < row; i++)
    {
        printf("%d", arr[i]);
        printf("\n");
    }
    return 0;
}